package com.webuploader.demo.controller;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * @Author xiang
 * @Date 2021/5/15 17:08
 * @Version 1.0
 */
@Controller
public class UploadControll {

    private  final  static String utf8="utf-8";
    @RequestMapping("/upload")
    @ResponseBody
    public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception{

        System.out.println("开始文件上次");
        //分片
        response.setCharacterEncoding(utf8);
        Integer schunk=null;
        Integer schunks=null;
        String name=null;
        //文件保存路径
        String uploadPath="F:\\fileItem";
        BufferedOutputStream os=null;
        try{
            DiskFileItemFactory factory=new DiskFileItemFactory();
            factory.setSizeThreshold(1024);
            factory.setRepository(new File(uploadPath));
            ServletFileUpload upload=new ServletFileUpload(factory);
            upload.setFileSizeMax(5L*1024L*1024L);
            upload.setSizeMax(10L*1024L*1024L);
            List<FileItem> items = upload.parseRequest(request);
            System.out.println("开始便利");
            for(FileItem item :items){
                System.out.println(item.toString());
                if(item.isFormField()){
                    if("chunk".equals(item.getFieldName())){
                        schunk= Integer.parseInt(item.getString(utf8));
                    }
                    if("chunks".equals(item.getFieldName())){
                        schunks= Integer.parseInt(item.getString(utf8));
                        System.err.println("总分片数："+schunks);
                    }
                    if("name".equals(item.getFieldName())){
                        name= item.getString(utf8);
                    }
                }
            }
            for(FileItem item :items){
                //判断是否是普通表单类型
                if(!item.isFormField()){
                    String temFileName=name;
                if(name != null){
                    if(schunk !=null){
                        temFileName= schunk+"_"+name;
                    }
                    File temFile=new File(uploadPath,temFileName);
                    //判断文件是否存在(判断分片文件是否存在)
                    if(!temFile.exists()){
                        item.write(temFile);
                    }
                }
                }
            }
            //判断是否有分片同时是最后一段分片(文件合并)
            if(schunk != null && schunk.intValue() == schunks.intValue()-1){
                System.err.println("进入文件合并："+schunks);
                File tempFile= new File(uploadPath,name);
                os=new BufferedOutputStream(new FileOutputStream(tempFile));
                //查找分片
                for(int i=0;i<schunks;i++){
                    System.err.println("查找分片:"+i);
                    File file=new File(uploadPath,i+"_"+name);
                    while (!file.exists()){
                        System.err.println("文件不存在："+i);
                        Thread.sleep(1);
                    }
                    //读取分片
                    byte [] bytes=FileUtils.readFileToByteArray(file);
                    os.write(bytes);
                    os.flush();
                    //删除分片文件
                    file.delete();
                    System.err.println("删除分片");
                }
                os.flush();
            }
                response.getWriter().write("上传成功");
                System.out.println("上传完成:"+name);
        }finally {
            try {
                if(os != null){
                    System.out.println("关闭文件流");
                    os.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }

        }
    }

    @RequestMapping("download1aa")
    public String downLoad(HttpServletResponse response) throws UnsupportedEncodingException {
        String filename="Photoshop 2021.zip";
        String filePath = "F:\\ps\\" ;
        File file = new File(filePath + "/" + filename);
        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String("报名照片.jpg".getBytes("gb2312"),"ISO_8859_1"));

            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;

            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download" + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }



}
